package cn.javasea.rbac.shiro.util;
/**
 * ***************************************************************************
 * Copyright. China Southern Airlines Holdings plc 2016 ALL RIGHTS RESERVED.
 * <p>
 * This software is only to be used for the purpose for which it
 * has been provided. No part of it is to be reproduced,
 * dissembled, transmitted, stored in a retrieval system or
 * translated in any human or computer language in any way or
 * for any other purposes whatsoever without the prior written
 * consent of China Southern Airlines Holdings plc.
 * ***************************************************************************
 * <p>
 * Class Name		IPUtil
 * <p>
 * Abstract
 * <p>
 * Amendment History (In chronological sequence):
 * Amendment Date：2017/7/20
 * Programmer: huangjun
 */

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author huangjun
 * @creation_date 2017/7/20
 * @version 1.0
 */
public class IPUtil {

    /**
     * 获取用户请求IP
     *
     * @param request
     * @return
     */
    public static String getUserIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取本机ip
     * @return
     * @throws SocketException
     */
    public static String getRealHost() throws SocketException {
        // 本地IP，如果没有配置外网IP则返回它
        String localIp = null;
        String netIp = null;
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        boolean found = false;
        while (netInterfaces.hasMoreElements() && !found) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                    netIp = ip.getHostAddress();
                    found = true;
                    break;
                } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                    localIp = ip.getHostAddress();
                }
            }
        }
        return (netIp != null && !"".equals(netIp)) ? netIp : localIp;
    }
}
